import datetime

from flask import session

from webapp.extensions import AppException
from webapp.models import Grade, db, User, UsersJobs, Job, UsersRoles, VTeacher, TeacherBindTime, LeaveInfo


class LeaveService:
    @staticmethod
    def create(curr_leaveinfo: LeaveInfo):
        leavetable: LeaveInfo = LeaveInfo.query.filter(LeaveInfo.uid == curr_leaveinfo.uid,
                                                       LeaveInfo.leavetime == curr_leaveinfo.leavetime).one_or_none()
        if leavetable:
            raise AppException(f'{curr_leaveinfo.leavetime}的请假已申请，请勿重复申请!')
        curr_leaveinfo.create_time = datetime.datetime.now()
        leaveInfoTable = LeaveInfo(
            uid=curr_leaveinfo.uid,
            username=curr_leaveinfo.username,
            nickname=curr_leaveinfo.nickname,
            tname=curr_leaveinfo.tname,
            reason=curr_leaveinfo.reason,
            leavetime=curr_leaveinfo.leavetime,
            status=curr_leaveinfo.status,
            create_time=curr_leaveinfo.create_time,
            create_by=curr_leaveinfo.nickname,
        )
        db.session.add(leaveInfoTable)
        db.session.commit()

    @staticmethod
    def query_leaveinfo_uid(data):
        uid = data.get("uid")
        leaveinfos = LeaveInfo.query.filter(LeaveInfo.uid == uid).paginate(
            int(0) + 1, per_page=int(1000),
            error_out=False)
        return leaveinfos
